package mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class MailHelper {
    public static boolean sendEmail(String host, String from, String pwd, String to, String subject,
                                    String content, List<String> files){
        try{
            //1.创建参数配置，用于连接邮件服务器的参数配置
            Properties properties=new Properties();
            properties.setProperty("mail.transport.protocol","smtp");
            properties.setProperty("mail.smtp.host",host);
            properties.setProperty("mail.smtp.auth","true");

            //2.根据配置创建会话对象，用于和邮件服务器交互
            Session session=Session.getInstance(properties);
            session.setDebug(true);//是否有debug信息
            //3.创建一封邮件
            //1.创建一封邮件
            MimeMessage mimeMessage=new MimeMessage(session);
            //2.from，发件人
            mimeMessage.setFrom(new InternetAddress(from,from,"UTF-8"));
            //3.To：收件人（可以增加多个收件人、抄送、密送）
            mimeMessage.setRecipients(MimeMessage.RecipientType.TO,new InternetAddress[]{new InternetAddress(to,to,"utf-8")});
            //4.邮件主题
            mimeMessage.setSubject(subject,"UTF-8");
            if(files.size()>0){//带附件邮件
                //创建邮件正文，为了避免邮件正文中中文乱码的问题，需要室友charset=utf-8指明字符编码
                MimeBodyPart text = new MimeBodyPart();
                text.setContent(content, "text/html;charset=UTF-8");
                //创建容器描述数据关系
                MimeMultipart mp=new MimeMultipart();
                mp.addBodyPart(text);
                for(String file:files){
                    //创建邮件附件
                    MimeBodyPart attach=new MimeBodyPart();
                    DataHandler dh=new DataHandler(new FileDataSource(file));
                    attach.setDataHandler(dh);
                    attach.setFileName(dh.getName());
                    mp.addBodyPart(attach);
                }
                mp.setSubType("mixed");//类型
                mimeMessage.setContent(mp,"text/html;charset=UTF-8");
            }
            else {
                //5.Content：邮件正文（可以用HTML标签）
                mimeMessage.setContent(content, "text/html;charset=UTF-8");
            }
            //6.设置发送时间
            mimeMessage.setSentDate(new Date());
            //7.保存设置
            mimeMessage.saveChanges();
            //4.根据Session获取邮件传输对象
            Transport transport=session.getTransport();
            //5.使用邮箱账号和密码连接邮件服务器，这里认证的邮箱必须与message中的发件人邮箱一直，否则报错
            transport.connect(from,pwd);
            //6.发送邮件，发送到所有的收件地址，message.getAllRecipient()获取到的是在创建邮件对象添加的所有
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
            //7.关闭连接
            transport.close();
            return true;
        }catch (Exception e){
            System.out.println("发送邮件失败！"+e.getMessage());
        }
        return false;
    }
}
